#ifndef __JSON_H__
#define __JSON_H__

#include <iostream>
using namespace std;
#include <string>
#include <vector>
#include <map>

namespace sf
{
    namespace json
    {
        class Json
        {
        public:
            enum Type
            {
                json_null = 0,
                json_bool,
                json_int,
                json_double,
                json_string,
                json_array,
                json_project
            };

            Json();
            Json(bool value);
            Json(int value);
            Json(double value);
            Json(const char *value);
            Json(const string &value);
            Json(Type type);
            Json(const Json &other); // 拷贝构造函数

            // 隐式类型转换
            operator bool();
            operator int();
            operator double();
            operator string();

            // 显示类型转换
            bool asBool() const;
            int asInt() const;
            double asDouble() const;
            string asString() const;

            void append(const Json &other);
            Json &operator[](int index);
            Json &operator[](const char *key);
            Json &operator[](const string &key);
            bool operator==(const Json &other);
            bool operator!=(const Json &other);

            // 类型判断
            inline bool isNull() const { return m_type == json_null; }
            inline bool isBool() const { return m_type == json_bool; }
            inline bool isInt() const { return m_type == json_int; }
            inline bool isDouble() const { return m_type == json_double; }
            inline bool isString() const { return m_type == json_string; }
            inline bool isArray() const { return m_type == json_array; }
            inline bool isObject() const { return m_type == json_project; }

            string str() const;
            void copy(const Json &other);
            void clear();

            bool has(int index);
            bool has(const char *key);
            bool has(const string &key);

            void remove(int index);
            void remove(const char *key);
            void remove(const string &key);

            void parse(const string &str);

            typedef std::vector<Json>::iterator iterator;
            inline iterator begin()
            {
                return m_value.m_array->begin();
            }
            inline iterator end()
            {
                return m_value.m_array->end();
            }

        private:
            union Value
            {
                bool m_bool;
                int m_int;
                double m_double;
                string *m_string;
                vector<Json> *m_array;
                map<string, Json> *m_object;
            };

            Type m_type;
            Value m_value;
        };
    }
}

#endif
